package com.face.gaoml.netlibrary;

import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 用于管理RxBus的事件和Rxjava相关代码的生命周期处理
 * Created by baixiaokang on 16/4/28.
 */
public class RxManager {

    public RxBus mRxBus = RxBus.$();
    private Map<String, Observable<?>> mObservables = new HashMap<>();// 管理观察源
    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();// 管理订阅者者


    public void on(String eventName, Action1<Object> action1) {
        Observable<?> mObservable = mRxBus.register(eventName);
        mObservables.put(eventName, mObservable);
        mCompositeSubscription.add(mObservable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(action1, new Action1<Throwable>(){

                    @Override
                    public void call(Throwable e) {
                        e.printStackTrace();
                    }
                }));
    }

    public void add(Subscription m) {
        mCompositeSubscription.add(m);
    }

    public void clear() {
        mCompositeSubscription.unsubscribe();// 取消订阅
        for (Map.Entry<String, Observable<?>> entry : mObservables.entrySet())
            mRxBus.unregister(entry.getKey(), entry.getValue());// 移除观察
    }

    public void post(Object tag, Object content) {
        mRxBus.post(tag, content);
    }




//    四、发送事件
//RxBus.getInstance().post(new StudentEvent("007","小明"));
//    五、接收事件
//            rxSbscription=RxBus.getInstance().toObserverable(StudentEvent.class)
//            .subscribe(new Action1<StudentEvent>() {
//                @Override
//                public void call(StudentEvent studentEvent) {
//                    textView.setText("id:"+ studentEvent.getId()+"  name:"+ studentEvent.getName());
//                }
//            });


    /**
     *
     * @param observable 要发送的请求
     * @param subscriber 请求 回来的处理
     */
    public void addSubscription(Observable observable, Subscriber subscriber) {
        mCompositeSubscription.add(
                observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }
}
